﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;

namespace AIC_Notification
{
    public class EssayPendingReportForAC : FormatedReport
    {
        public IList<SOF_Application> Students = null;
        public IList<RallySchoolStatistics> RallySchoolStatsList = null;
        public Teacher TeacherInContext = null;

        // List for sorting
        private Dictionary<string, string> PendingRevisionRows;
        private Dictionary<string, string> PendingDraftRows;
        private int ItemCounter = 0;
        public bool ShowWarning = false;
        public bool ShowStudentSection = false;
        public int DisplayPendingDays;

        public EssayPendingReportForAC(bool ShowDetail = false)
        {
            ReportTitle = "Draft Pending Revision (Consultant)";
            ShowWarning = ShowDetail;
            ShowStudentSection = true;
            DisplayPendingDays = 0;
        }

        public override void SendReportAsEmail()
        {
            foreach (var _teacher in TeacherDB.Teachers)
            {
                string HTMLBody;

                if (_teacher.Students.Count > 0)
                {
                    Students = _teacher.Students;
                    RallySchoolStatsList = _teacher.RallySchoolStatsList;
                    TeacherInContext = _teacher;
                    HeaderInformation = _teacher.Name;

                    FileName = String.Format("{0}-{1}-{2:yyyyMMdd-HHmmss}.htm", ReportTitle, _teacher.Name, Global.Now());
                    Global.SysUtil.Log("Generating Report: " + FileName);

                    HTMLBody = GetHTMLBody();

                    // Save Report to File
                    SaveReportToFile(FileName, HTMLBody);

                    // Send Report E-mail
                    toRecipients.Clear();
                    ccRecipients.Clear();

                    toRecipients.Add(_teacher.Email);

                    // Copy e-mail to extra recipients if not empty
                    if (!IsEmptyBody)
                    {
                    }

                    SubjectID = _teacher.Name;

                    Global.SysUtil.SendHTML(toRecipients, ccRecipients, GetSubject(), HTMLBody);
                }
            }
        }

        public override string GenerateLedger()
        {
            string htmlLedger = "";

            htmlLedger += "<tr><td>";
            htmlLedger += "<table align=\"center\" style=\"margin-left:auto; margin-right: auto; border: 0px solid black; border-collapse: collapse;\"><tr>";
            htmlLedger += "<td style=\"font-size: 12px; \">White: 1-2 days </td>";
            htmlLedger += "<td style=\"font-size: 12px; background-color: #FFDDAA;\">Orange: 3 days </td>";
            htmlLedger += "<td style=\"font-size: 12px; background-color: #F8D3D3;\">Red:  over 3 days </td>";
            htmlLedger += "<td style=\"font-size: 12px; background-color: #FFFFCC;\">Yellow:  Issues (See Note) </td>";
            htmlLedger += "</tr></table>";
            htmlLedger += "</td></tr>"; 

            return htmlLedger;
        }

        public virtual string InsertTeachersName(SOF_Application student)
        {
            string tableBody = "";

            tableBody += "<td><div>";
            tableBody += String.Format("<div><div style=\"font-size: {1}px; {2}\">PT: {0}</div></div>", student.AC_PT, 11, student.AC_PT == TeacherInContext.Name ? "color: blue" : "");
            if (student.AC_ST != "")
                tableBody += String.Format("<div><div style=\"font-size: {1}px; {2}\">ST: {0}</div></div>", student.AC_ST, 11, student.AC_ST == TeacherInContext.Name ? "color: blue" : "");
            tableBody += String.Format("<div><div style=\"font-size: {1}px; {2}\">EC: {0}</div></div>", student.EC, 11, student.EC == TeacherInContext.Name ? "color: blue" : "");
            tableBody += "</div></td>";

            return tableBody;
        }

        public bool ShowRevisionRow(EssayStatistics EssayStats)
        {
            bool DisplayRow;

            if (EssayStats.HasRevisionPending && EssayStats.PendingTimeSpan.TotalDays >= DisplayPendingDays)
            {
                if (EssayStats.MissingDueDate)
                    DisplayRow = ShowWarning;
                else
                    DisplayRow = true;
            }
            else if (ShowWarning && (EssayStats.MissingFinalTag || EssayStats.MissingAttachment))
            {
                DisplayRow = true;
            }
            else
                DisplayRow = false;

            return DisplayRow;
        }

        public virtual bool ShowDraftRow(EssayStatistics EssayStats)
        {
            bool DisplayRow;

            if (EssayStats.HasOverDuedDraft)
                DisplayRow = true;
            else if (EssayStats.MissingDueDate)
                DisplayRow = ShowWarning;
            else
                DisplayRow = false;

            return DisplayRow;
        }

        private string EssayName(string SchoolName, int EssayNumber, int LatestDraft, string Url)
        {
            string EssayHTML = "";
            bool IsBrainstorm = LatestDraft < 0 ? true : false;
            int DraftNumber = LatestDraft < 0 ? LatestDraft + 50 : LatestDraft;

            if (SchoolName == "CEF")
            {
                if (EssayNumber == 1)
                    EssayHTML += String.Format("<td style=\"font-size: 14px;\"><a href=\"{0}\">CEF-D{1}</a></td>", Url, DraftNumber);
                else if (EssayNumber == 2)
                    EssayHTML += String.Format("<td style=\"font-size: 14px;\"><a href=\"{0}\">CER</a></td>", Url);
            }
            else if (SchoolName == "PS")
                EssayHTML += String.Format("<td style=\"font-size: 14px;\"><a href=\"{0}\">PS-T{1}-D{2}</a></td>", Url, EssayNumber, DraftNumber);
            else if (SchoolName == "HAL")
            {
                if (EssayNumber == 1)
                    EssayHTML += String.Format("<td style=\"font-size: 14px;\"><a href=\"{0}\">HAL-MAJ-D{1}</a></td>", Url, DraftNumber);
                else if (EssayNumber == 2)
                    EssayHTML += String.Format("<td style=\"font-size: 14px;\"><a href=\"{0}\">HAL-D{1}</a></td>", Url, DraftNumber);
            }
            else
                EssayHTML += String.Format("<td style=\"font-size: 14px;\"><a href=\"{0}\">E{1}-{2}D{3}</a></td>", Url, EssayNumber, IsBrainstorm ? "BS-" : "", DraftNumber);

            return EssayHTML;
        }

        private void InsertRow(Dictionary<string, string> Table, string tableRowKey, string itemColor, SOF_Application student, string ListName, string EssayHTML, string DateHTML, string OverdueHTML, string NoteHTML)
        {
            string tableRowValue = "";

            tableRowValue += String.Format("<tr style=\"background-color: {0};\">", itemColor);

            tableRowValue += String.Format("<td style=\"font-size: 14px;\"><a href=\"{0}\">{1}</a></td>", student.Url, WebUtility.HtmlEncode(student.Name));
            tableRowValue += InsertTeachersName(student);
            tableRowValue += String.Format("<td style=\"font-size: 14px;\">{0}</td>", WebUtility.HtmlEncode(ListName));
            tableRowValue += EssayHTML;

            tableRowValue += DateHTML;
            tableRowValue += OverdueHTML;

            tableRowValue += String.Format("<td style=\"font-size: 11px;\">{0}</td>", WebUtility.HtmlEncode(NoteHTML));
            
            tableRowValue += "</tr>";

            Table.Add(tableRowKey, tableRowValue);
        }

        private void InsertPendingDraftRows(SOF_Application student, string SchoolName, SchoolStatistics SchoolStats, bool DisplayAllDraft = false)
        {
            if (SchoolName.StartsWith("UC-", StringComparison.CurrentCultureIgnoreCase))
                SchoolName = "UC";

            foreach (var EssayStats in SchoolStats.EssayStatisticsList)
            {
                if (EssayStats.HasIssue && (EssayStats.MissingDueDate || EssayStats.HasOverDuedDraft))
                {
                    string tableRowKey = "";
                    string essayHTML = "";
                    string noteHTML = "";
                    string itemColor = "";
                    string DateHTML = "";
                    string OverdueHTML = "";
                    bool IsOverDued = false;

                    TimeSpan WorkingTimeSpan = TimeSpan.Zero;
                    double WorkingDays = 0;

                    if (EssayStats.HasOverDuedDraft)
                    {
                        if (EssayStats.PendingDraftObject.DueDate < Global.Now())
                        {
                            IsOverDued = true;
                            WorkingTimeSpan = Global.Now() - EssayStats.PendingDraftObject.DueDate;
                        }
                        else
                        {
                            IsOverDued = false;
                        }
                        WorkingDays = WorkingTimeSpan.TotalDays;
                    }

                    if (!ShowDraftRow(EssayStats))
                        continue;

                    if (EssayStats.HasOverDuedDraft)
                        tableRowKey = String.Format("3-{0}-{1:000.00}-{2}", student.Name, 999-WorkingDays, ItemCounter);
                    else
                        tableRowKey = String.Format("2-{0}-000.00-{1}", student.Name, ItemCounter);

                    ItemCounter += 1;

                    // Set Color
                    if (WorkingDays < 7)
                        itemColor = ""; // "#ccffcc;"; Green
                    else if ((WorkingDays > 7) && (WorkingDays < 14))
                        itemColor = "#FFDDAA"; // Orange
                    else
                        itemColor = "#F8D3D3"; // Red

                    if (EssayStats.MissingDueDate)
                        itemColor = "#FFFFCC"; // Yellow

                    // Handle New Empty Draft Cards
                    essayHTML = EssayName(SchoolName, EssayStats.EssayNumber, EssayStats.PendingDraftObject.DraftNumber, EssayStats.PendingDraftObject != null ? EssayStats.PendingDraftObject.Url : "");
                    noteHTML = EssayStats.PendingDraftObject != null ? EssayStats.PendingDraftObject.Note : "";

                    // Build row if essayHTML not empty
                    if (essayHTML != "")
                    {
                        if (EssayStats.HasOverDuedDraft)
                        {
                            DateHTML = String.Format("<td style=\"font-size: 14px;\">{0:g}</td>", EssayStats.PendingDraftObject.DueDate);
                            if (IsOverDued)
                            {
                                OverdueHTML = String.Format("<td style=\"font-size: 14px;\">{0:%d}</td>", WorkingTimeSpan);
                            }
                            else
                            {
                                OverdueHTML = String.Format("<td style=\"font-size: 14px;\">Not Due Yet</td>");
                            }
                        }
                        else
                        {
                            DateHTML = String.Format("<td style=\"font-size: 14px;\">N/A</td>");
                            OverdueHTML = String.Format("<td style=\"font-size: 14px;\">N/A</td>");
                        }

                        if (IsOverDued)
                        {
                            InsertRow(PendingDraftRows, tableRowKey, itemColor, student, SchoolName, essayHTML, DateHTML, OverdueHTML, noteHTML);
                        }
                        else
                        {
                            if (DisplayAllDraft)
                                InsertRow(PendingDraftRows, tableRowKey, itemColor, student, SchoolName, essayHTML, DateHTML, OverdueHTML, noteHTML);
                        }
                    }
                }
            }
        }

        private void InsertPendingRevisionRows(SOF_Application student, string SchoolName, SchoolStatistics SchoolStats)
        {
            if (SchoolName.StartsWith("UC-", StringComparison.CurrentCultureIgnoreCase))
                SchoolName = "UC";

            foreach (var EssayStats in SchoolStats.EssayStatisticsList)
            {
                if (EssayStats.HasIssue && (EssayStats.HasRevisionPending || EssayStats.MissingFinalTag || EssayStats.MissingAttachment))
                {
                    string tableRowKey = "";
                    string essayHTML = "";
                    string noteHTML = "";
                    string itemColor;
                    string DateHTML = "";
                    string OverdueHTML = "";

                    TimeSpan WorkingTimeSpan = TimeSpan.Zero;
                    double WorkingDays = 0;

                    if (!ShowRevisionRow(EssayStats))
                        continue;

                    if (EssayStats.HasRevisionPending)
                    {
                        WorkingTimeSpan = EssayStats.PendingTimeSpan;
                        WorkingDays = WorkingTimeSpan.TotalDays;
                    }

                    if (EssayStats.HasRevisionPending)
                        tableRowKey = String.Format("3-{0:000.00}-{1}-{2}", WorkingDays, student.Name, ItemCounter);
                    else
                        tableRowKey = String.Format("1-000.00-{0}-{1}", student.Name, ItemCounter);

                    ItemCounter += 1;

                    // Set Color
                    if (WorkingDays < 2)
                        itemColor = ""; // "#ccffcc;"; Green
                    else if ((WorkingDays > 2) && (WorkingDays < 3))
                        itemColor = "#FFDDAA"; // Orange
                    else
                        itemColor = "#F8D3D3"; // Red

                    if (EssayStats.MissingFinalTag || EssayStats.MissingAttachment)
                        itemColor = "#FFFFCC"; // Yellow 

                    // Handle New Empty Draft Cards
                    essayHTML = EssayName(SchoolName, EssayStats.EssayNumber, EssayStats.LatestDraft, EssayStats.DraftObject != null ? EssayStats.DraftObject.Url : "");
                    noteHTML = EssayStats.DraftObject != null ? EssayStats.DraftObject.Note : "";

                    // Build row if essayHTML not empty
                    if (essayHTML != "")
                    {
                        if (EssayStats.HasRevisionPending)
                        {
                            DateHTML = String.Format("<td style=\"font-size: 14px;\">{0:g}</td>", EssayStats.DraftAttachmentDate);
                            if (WorkingDays < 1)
                                OverdueHTML = String.Format("<td style=\"font-size: 14px;\">&lt; 1</td>");
                            else if ((WorkingDays > 2) && (WorkingDays < 4))
                                OverdueHTML = String.Format("<td style=\"font-size: 14px;\">{0:%d}d {1:%h}h</td>", WorkingTimeSpan, WorkingTimeSpan);
                            else
                                OverdueHTML = String.Format("<td style=\"font-size: 14px;\">{0:%d}</td>", WorkingTimeSpan);
                        }
                        else
                        {
                            DateHTML = String.Format("<td style=\"font-size: 14px;\">N/A</td>");
                            OverdueHTML = String.Format("<td style=\"font-size: 14px;\"> Idle &gt; 1 month</td>");
                        }

                        InsertRow(PendingRevisionRows, tableRowKey, itemColor, student, SchoolName, essayHTML, DateHTML, OverdueHTML, noteHTML);

                        toRecipients.Add(TeacherDB.GetTeacherEmailByName(student.AC_PT));
                    }
                }
            }
        }

        public override string InnerTableHeader()
        {
            return "";
            // return "<tr><th style=\"font-size: 14px;\">Students</th><th style=\"font-size: 14px;\">Consultants</th><th style=\"font-size: 14px;\">Schools</th><th style=\"font-size: 14px;\">Essay-Drafts</th><th style=\"font-size: 14px;\">Draft Date</th><th style=\"font-size: 14px;\"># Days Pending</th><th style=\"font-size: 14px;\">Note</th></tr>";
        }

        public override string EmptyInnerTable()
        {
            return "<tr><td style=\"padding: 10px 10px 10px 10px; text-align:center;\">No Essay Pending</td></tr>";
        }

        public override string GenerateInnerTable()
        {
            string tableRevisionHeader = "";
            string tableDraftHeader = "";
            string tableRevisionBody = "";
            string tableDraftBody = "";
            string tableBody = "";

            IList<Essay> Essays;

            SetWidth(60); // Set table width %
            PendingRevisionRows = new Dictionary<string, string>();
            PendingDraftRows = new Dictionary<string, string>();

            var StudentsByName = Students.OrderBy(SOF_Application => SOF_Application.Name).ToList(); // Order by student Name

            foreach (var student in StudentsByName)
            {
                if (student.Schools != null)
                {
                    foreach (var school in student.Schools)
                    {
                        if (school != null)
                        {
                            Essays = school.Essays;
                            if (Essays != null)
                            {
                                InsertPendingRevisionRows(student, school.School, school.SchoolStats);
                                if (ShowStudentSection)
                                {
                                    if (TeacherInContext.Type == "Education Consultant")
                                        InsertPendingDraftRows(student, school.School, school.SchoolStats, true);
                                    else
                                        InsertPendingDraftRows(student, school.School, school.SchoolStats, false);
                                }
                            }
                        }
                    }
                }
            }

            // Sort by key
            PendingRevisionRows = PendingRevisionRows.OrderByDescending(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
            PendingDraftRows = PendingDraftRows.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);

            // Insert value into table
            foreach (var TableRow in PendingRevisionRows.Values)
                tableRevisionBody += TableRow;

            foreach (var TableRow in PendingDraftRows.Values)
                tableDraftBody += TableRow;

            if (TeacherInContext != null)
            {
                if (TeacherInContext.Type == "Academic Consultant" || TeacherInContext.Type == "Both")
                {
                    tableRevisionHeader += "<tr><th colspan = \"7\" style=\"background-color: #483D8B; color: white;\">Consultant: Pending Revision</th></tr>";
                    tableRevisionHeader += "<tr><th style=\"font-size: 14px;\">Students</th><th style=\"font-size: 14px;\">Consultants</th><th style=\"font-size: 14px;\">Schools</th><th style=\"font-size: 14px;\">Essay-Drafts</th><th style=\"font-size: 14px;\">Draft Date</th><th style=\"font-size: 14px;\"># Days Pending</th><th style=\"font-size: 14px;\">Note</th></tr>";
                    if (tableRevisionBody == "")
                        tableRevisionBody += "<tr><td colspan = \"7\" style=\"background-color: #CCFFCC;\">No Revision Pending</td></tr>";
                    tableBody += tableRevisionHeader + tableRevisionBody;

                    tableDraftHeader += "<tr><th colspan = \"7\"></th></tr>";

                    // Insert value into table
                    tableDraftHeader += "<tr><th colspan = \"7\" style=\"background-color: #483D8B; color: white;\">Student: Overdue Draft</th></tr>";
                    tableDraftHeader += "<tr><th style=\"font-size: 14px;\">Students</th><th style=\"font-size: 14px;\">Consultants</th><th style=\"font-size: 14px;\">Schools</th><th style=\"font-size: 14px;\">Essay-Drafts</th><th style=\"font-size: 14px;\">Due Date</th><th style=\"font-size: 14px;\">Overdue by # Days</th><th style=\"font-size: 14px;\">Note</th></tr>";
                    if (tableDraftBody == "")
                        tableDraftBody += "<tr><td colspan = \"7\" style=\"background-color: #CCFFCC;\">No Draft Due</td></tr>";
                    tableBody += tableDraftHeader + tableDraftBody;
                }
                else if (TeacherInContext.Type == "Education Consultant")
                {
                    // Insert value into table
                    tableDraftHeader += "<tr><th colspan = \"7\" style=\"background-color: #483D8B; color: white;\">Student: Overdue Draft</th></tr>";
                    tableDraftHeader += "<tr><th style=\"font-size: 14px;\">Students</th><th style=\"font-size: 14px;\">Consultants</th><th style=\"font-size: 14px;\">Schools</th><th style=\"font-size: 14px;\">Essay-Drafts</th><th style=\"font-size: 14px;\">Due Date</th><th style=\"font-size: 14px;\">Overdue by # Days</th><th style=\"font-size: 14px;\">Note</th></tr>";
                    if (tableDraftBody == "")
                        tableDraftBody += "<tr><td colspan = \"7\" style=\"background-color: #CCFFCC;\">No Draft Due</td></tr>";
                    tableBody += tableDraftHeader + tableDraftBody;

                    tableDraftHeader += "<tr><th colspan = \"7\"></th></tr>";

                    tableRevisionHeader += "<tr><th colspan = \"7\" style=\"background-color: #483D8B; color: white;\">Consultant: Pending Revision</th></tr>";
                    tableRevisionHeader += "<tr><th style=\"font-size: 14px;\">Students</th><th style=\"font-size: 14px;\">Consultants</th><th style=\"font-size: 14px;\">Schools</th><th style=\"font-size: 14px;\">Essay-Drafts</th><th style=\"font-size: 14px;\">Draft Date</th><th style=\"font-size: 14px;\"># Days Pending</th><th style=\"font-size: 14px;\">Note</th></tr>";
                    if (tableRevisionBody == "")
                        tableRevisionBody += "<tr><td colspan = \"7\" style=\"background-color: #CCFFCC;\">No Revision Pending</td></tr>";
                    tableBody += tableRevisionHeader + tableRevisionBody;
                }
            }
            else
            {
                tableRevisionHeader += "<tr><th colspan = \"7\" style=\"background-color: #483D8B; color: white;\">Consultant: Pending Revision</th></tr>";
                tableRevisionHeader += "<tr><th style=\"font-size: 14px;\">Students</th><th style=\"font-size: 14px;\">Consultants</th><th style=\"font-size: 14px;\">Schools</th><th style=\"font-size: 14px;\">Essay-Drafts</th><th style=\"font-size: 14px;\">Draft Date</th><th style=\"font-size: 14px;\"># Days Pending</th><th style=\"font-size: 14px;\">Note</th></tr>";
                if (tableRevisionBody == "")
                    tableRevisionBody += "<tr><td colspan = \"7\" style=\"background-color: #CCFFCC;\">No Revision Pending</td></tr>";
                tableBody += tableRevisionHeader + tableRevisionBody;

                if (ShowStudentSection)
                {
                    // Insert value into table
                    if (tableDraftBody != "")
                    {
                        tableDraftHeader += "<tr><th colspan = \"7\"></th></tr>";
                        tableDraftHeader += "<tr><th colspan = \"7\" style=\"background-color: #483D8B; color: white;\">Student: Overdue Draft</th></tr>";
                        tableDraftHeader += "<tr><th style=\"font-size: 14px;\">Students</th><th style=\"font-size: 14px;\">Consultants</th><th style=\"font-size: 14px;\">Schools</th><th style=\"font-size: 14px;\">Essay-Drafts</th><th style=\"font-size: 14px;\">Due Date</th><th style=\"font-size: 14px;\">Overdue by # Days</th><th style=\"font-size: 14px;\">Note</th></tr>";
                        if (tableDraftBody == "")
                            tableDraftBody += "<tr><td colspan = \"7\" style=\"background-color: #CCFFCC;\">No Draft Due</td></tr>";
                        tableBody += tableDraftHeader + tableDraftBody;
                    }
                }
            }

            return tableBody;
        }
    }
}
